import pygtk
import gtk
import gtk.glade
import libuji
import xml.parsers.expat
import xml.dom.minidom
class GladeHandlers:
    def on_txtPasswd_key_press_event(entry, event):
        print event.keyval
        print entry
        if event.keyval == 65293:
            print 'enter pressed'
            autenticar()

    def on_btnEnviar_clicked(event):

        strTelefon = txtTelefon.get_text()
        buffer = txtMissatge.get_buffer()
        strMissatge = buffer.get_text(buffer.get_start_iter(),buffer.get_end_iter())        

        if len(strMissatge) <= 125 and len(strMissatge) > 0 and len(strTelefon) >= 9:
            lblSms.set_text('Enviant sms...')
            lblSms.set_text(libuji.sendSms(strTelefon, strMissatge))
        elif len(strTelefon) < 9:
            lblSms.set_text('Numero de telefon incorrecte')
        elif len(strMissatge) == 0:
            lblSms.set_text('No has escrit res al cos del missatge!')
        else:
            lblSms.set_text('Has escrit mes de 125 caracters')
            
    def on_txtMissatge_key_press_event(entry, event):
        buffer = txtMissatge.get_buffer()
        strMissatge = buffer.get_text(buffer.get_start_iter(),buffer.get_end_iter())
        c = 125 - len(strMissatge)
        lblCaracters.set_text(str(c))
            
    def on_btnBorrar_clicked(event):
        buffer = txtMissatge.get_buffer()
        buffer.set_text('')
        txtMissatge.set_buffer(buffer)
        lblCaracters.set_text('125')
        
    def on_quit1_activate(event):
        gtk.main_quit()
    
    def on_btnAuthCancel_clicked(event):
        gtk.main_quit()

    def on_btnAuthOk_clicked(event):
        autenticar()

    def on_cmbContactes_changed(event):
        s = cmbContactes.get_active_text()
        s = s.split("(")[1]
        s = s.split(")")[0]
        txtTelefon.set_text(s)

    def on_btnAgregar_clicked(event):
        nom = txtContacteNom.get_text()
        tel = txtContacteTelefon.get_text()
        insertar_contacte(nom, tel)

    def on_btnCancelar_clicked(event):
        wContacte.hide() 

    def on_btnModificar_clicked(event):
        nom = txtContacteNom.get_text()
        tel = txtContacteTelefon.get_text()
        eliminar_contacte(numContacte)
        insertar_contacte(nom, tel)
        
    def on_btnNew_clicked(event):
        btnAgregar.show()
        btnModificar.hide()
        txtContacteNom.set_text('')
        txtContacteTelefon.set_text('')
        wContacte.show()
        
    def on_btnEdit_clicked(event):
        global nomContacte
        global numContacte
        s = cmbContactes.get_active_text()
        if s != '':
            numContacte = s.split("(")[1]
            numContacte = numContacte.split(")")[0]
            nomContacte = s.split("(")[0]
            nomContacte = nomContacte.strip()
            dom = carregar_dades('agenda.xml')
            for node in dom.childNodes:
                for node2 in node.childNodes:
                    if numContacte == node2.getAttribute(u'numero') and nomContacte == node2.getAttribute(u'nom'):
                        txtContacteNom.set_text(nomContacte)
                        txtContacteTelefon.set_text(numContacte)
                        btnAgregar.hide()
                        btnModificar.show()
                        wContacte.show()
                    
    def on_btnDelete_clicked(event):
        s = cmbContactes.get_active_text()
        if s != '':
            num = s.split("(")[1]
            num = num.split(")")[0]
            nom = s.split("(")[0]
            nom = nom.strip()
            eliminar_contacte(num)
    
    def on_btnAboutOk_clicked(event):
        wAbout.hide()
        
    def on_about1_activate(event):
        wAbout.show()
            
class Widgets:
    def __init__(self,file):
        self.widgets = gtk.glade.XML(file)
        global wAuth
        global wPrincipal
        global wAbout
        global txtTelefon
        global txtMissatge
        global usuari
        global password
        global lblSms
        global lblAuth
        global lblCaracters
        global lblAlerta
        global lblSms
        global cmbContactes
        global btnAgregar
        global btnModificar
        global btnEliminar
        global btnNew
        global btnEdit
        global btnDelete
        global txtContacteNom
        global txtContacteTelefon
        global wContacte

        cmbContactes = gtk.glade.XML.get_widget(self.widgets, "cmbContactes")
        usuari = gtk.glade.XML.get_widget(self.widgets, "txtUser")
        password = gtk.glade.XML.get_widget(self.widgets, "txtPasswd")
        txtTelefon = gtk.glade.XML.get_widget(self.widgets, "txtTelefon")
        txtMissatge = gtk.glade.XML.get_widget(self.widgets, "txtMissatge")
        lblAuth = gtk.glade.XML.get_widget(self.widgets, "lblAuth")
        lblCaracters = gtk.glade.XML.get_widget(self.widgets, "lblCaracters")
        lblAlerta = gtk.glade.XML.get_widget(self.widgets, "lblAlerta")
        lblSms = gtk.glade.XML.get_widget(self.widgets, "smsRestantes")
        btnAgregar = gtk.glade.XML.get_widget(self.widgets, "btnAgregar")
        btnModificar = gtk.glade.XML.get_widget(self.widgets, "btnModificar")
        btnEliminar = gtk.glade.XML.get_widget(self.widgets, "btnEliminar")
        btnNew = gtk.glade.XML.get_widget(self.widgets, "btnNew")
        btnEdit = gtk.glade.XML.get_widget(self.widgets, "btnEdit")
        btnDelete = gtk.glade.XML.get_widget(self.widgets, "btnDelete")
        txtContacteNom = gtk.glade.XML.get_widget(self.widgets, "txtContacteNom")
        txtContacteTelefon = gtk.glade.XML.get_widget(self.widgets, "txtContacteTelefon")
        
        wAuth = gtk.glade.XML.get_widget(self.widgets, "winAuth")
        wPrincipal = gtk.glade.XML.get_widget(self.widgets, "winPrincipal")
        wContacte = gtk.glade.XML.get_widget(self.widgets, "winContacte")
        wAbout = gtk.glade.XML.get_widget(self.widgets, "winAbout")
        wPrincipal.hide()
        wContacte.hide()
        wAbout.hide()
        self.widgets.signal_autoconnect(GladeHandlers.__dict__)

    def __getitem__(self,key):
        return self.widgets.get_widget(key)
    
def insertar_contacte(nom, tel):
    if len(nom) > 0 and len(tel) >= 9:
        dom = carregar_dades('agenda.xml')
        root = dom._get_firstChild()
        elem = dom.createElement('contacte')
        elem.setAttributeNS(None, 'nom', nom)
        elem.setAttributeNS(None, 'numero', tel)
        for node in dom.childNodes:
            for node2 in node.childNodes:
                if nom < node2.getAttribute(u'nom'):
                    root.insertBefore(elem, node2)
                    f = open('agenda.xml','w')
                    f.write(dom.toxml())
                    f.close()
                    cmbContactes.append_text(nom + ' (' + tel + ')')
                    wContacte.hide()
                    return
        root.appendChild(elem)
        f = open('agenda.xml','w')
        f.write(dom.toxml())
        f.close()
        cmbContactes.append_text(nom + ' (' + tel + ')')
        wContacte.hide()

def eliminar_contacte(tel):
    dom = carregar_dades('agenda.xml')
    for node in dom.childNodes:
        for node2 in node.childNodes:
            if tel == node2.getAttribute(u'numero'):
                f = open('agenda.xml', 'w')
                node.removeChild(node2)
                cmbContactes.remove_text(cmbContactes.get_active())
                f.write(dom.toxml())
                f.close()
def agenda():
    # 3 handler functions
    
    def start_element(name, attrs):
        if name == 'contacte':
            cmbContactes.append_text(attrs[u'nom'] + ' (' + attrs[u'numero'] + ')')

    p = xml.parsers.expat.ParserCreate()

    p.StartElementHandler = start_element
    
    #cmbContactes.clear()
    f = open("agenda.xml")
    p.Parse(str(f.read()), 1)
    
    f.close()

def carregar_dades(fitxer):
    f = open(fitxer)
    dom = xml.dom.minidom.parseString(f.read())
    f.close()
    return dom

def autenticar():
    u = usuari.get_text()
    p = password.get_text()
    if u != '' and p != '':
        smsRestants = libuji.getNumeroSms(u, p)
        if smsRestants != -1:
            wAuth.hide()
            wPrincipal.show()
            lblSms.set_text(smsRestants)
        else:
            lblAuth.set_text('Usuari o contrasenya incorrectes!')
            usuari.set_text('')
            password.set_text('')
        
widgets = Widgets('uji-sms.glade')
wAuth.connect("delete_event", gtk.main_quit)
wPrincipal.connect("delete_event", gtk.main_quit)
agenda()
gtk.main()

